# coding=utf-8
import os
import sys
import time
import argparse
import binascii
from ctypes import *

class hex_head(BigEndianStructure):
    _pack_ = 1
    _fields_ = [
        ('len', c_uint8),
        ('address', c_uint16),
        ('type', c_uint8),
    ]

def printf_except_info(e):
    msg = '{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    # QMessageBox.information('错误',msg)
    print(msg)
    return msg
(
    TYPE_DATA_RECORD, #0
    TYPE_END_RECORD, #1
    TYPE_EXT_SEG_ADDR_RECORD, #2
    TYPE_START_SEG_ADDR_RECORD,#3
    TYPE_EXT_LINEAR_ADDR_RECORD,#4
    TYPE_START_LINEAR_ADDR_RECORD
) = range(0,6)

(
    ERR_NONE,
    ERR_FORMAT,
    ERR_LEN,
    ERR_EXCEPT,
) = range(0,4)

def get_sum(data):
    sum = 0
    for i in range(0, len(data)):
        sum += data[i]
    return (0x100 - sum) & 0xff

def get_sum_s19(data):
    sum = 0
    for i in range(0, len(data)):
        sum += data[i]
    return (0xff - sum) &0xff

def get_hex_info(src_name:str):
    try:
        hd = open(src_name,'r')

        if hd == None:
            return (ERR_NONE,'not file.')

        data_lines = hd.readlines()
        hd.close()
        temp = {}
        idx = 0
        offset_addr = None
        base_addr = None

        for line in data_lines:
            idx += 1
            if line[0] != ':' or line[-1] != '\n':
                return (ERR_FORMAT,'format err.{}.'.format(line))
            bin_data = bytearray(binascii.a2b_hex(line[1:-1])) 

            if len(bin_data) < len(bytearray(hex_head())) + 1:
                return (ERR_FORMAT, 'format {}'.format(line))

            frame = hex_head.from_buffer(bin_data)
            # print('len:%d address:0x%x type:%x'%(frame.len, frame.address, frame.type))
            if len(bin_data) != frame.len + len(bytearray(hex_head())) + 1:
                return (ERR_FORMAT, 'format {}'.format(line))
            sum = get_sum(bin_data[:-1])

            if bin_data[-1] != sum:
                return (ERR_FORMAT, 'format {} sum:{} {}'.format(line, sum, bin_data[-1]))

            if frame.type > TYPE_START_LINEAR_ADDR_RECORD:
                return (ERR_FORMAT, 'format err:type:{}'.format(frame.type))

            if frame.type == TYPE_EXT_LINEAR_ADDR_RECORD:
                base_addr = int('%02X%02X'%(bin_data[-3],bin_data[-2]), 16)<<16
                offset_addr = None
            elif frame.type == TYPE_DATA_RECORD and base_addr != None:
                temp_address = base_addr + frame.address
                find_key = None
                for key in temp.keys():
                    if key + len(temp[key]) == temp_address:
                        find_key = key
                        break
                if find_key == None:
                    find_key = temp_address
                    temp[find_key] = bytearray(0)
                temp[find_key].extend(bin_data[len(bytearray(hex_head())):len(bytearray(hex_head()))+ frame.len])  

        return (ERR_NONE, temp)

    except Exception as e:
        return (ERR_EXCEPT, '{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e))

def bin_to_hex(src_name:str,address:int, out_name:str):
    if os.path.exists(src_name) is False:
        return False


def get_s19_data(src_name):
    try:
        hd = open(src_name,'r')

        if hd == None:
            return (ERR_NONE,'not file.')

        data_lines = hd.readlines()
        hd.close()
        temp = {}
        idx = 0
        offset_addr = None
        base_addr = None

        for line in data_lines:
            idx += 1
            cmd = line[:2]
            size = int(line[2:4], 16)
            sum_data =  get_sum_s19(binascii.a2b_hex(line[2:-3]))
            # print('cmd:%s size:%d data:%s sum:0x%x 0x%x'%(cmd, size, line[4:-1], int(line[-3:-1],16), sum_data))
            addr_size = 0
            size_map = {'S1':2,'S2':3,'S3':4}
            if sum_data != int(line[-3:-1],16):
                return (ERR_FORMAT, 'sum err:{}'.format(line))

            if cmd in size_map.keys():
                addr_size = size_map[cmd]
                address = 0
                if addr_size == 2:
                    address = int(line[4:8],16)
                elif addr_size == 3:
                    address = int(line[4:10],16)
                elif addr_size == 4:
                    address = int(line[4:12],16)
                # print('addr_size:%d address:0x%x'%(addr_size, address))
                find_key = None
                for key in temp.keys():
                    if key + len(temp[key]) == address:
                        find_key = key
                        break
                if find_key == None:
                    find_key = address
                    temp[find_key] = bytearray(0)
                temp[find_key].extend(binascii.a2b_hex(line[4+ addr_size*2:-3]))  

        return (ERR_NONE, temp)

    except Exception as e:
        return (ERR_EXCEPT, '{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e))

if __name__ == '__main__':
    ret = get_hex_info('./test.hex')
    if ret[0] == ERR_NONE:
        for key, val in ret[1].items():
            print('address:0x%x len:%d data:%s'%(key, len(val), binascii.hexlify(val)))
    ret = get_s19_data('./tes.s19')
    if ret[0] == ERR_NONE:
        for key, val in ret[1].items():
            print('addr:0x%x size:%d data:%s'%(key,len(val),binascii.hexlify(val)))

    pass